$(function() {
    $( document ).tooltip();
    $("#loading").hide();
    $(document).bind("ajaxSend", function(){
        $("#loading").show();
    }).bind("ajaxComplete", function(){
        $("#loading").hide();
    });
    var pseudo = $("#pseudo"),
    isadmin = $("#isadmin"),
    name = $( "#name" ),
    firstname= $("#firstname"),
    email = $( "#email" ),
    location = $( "#location" ),
    allFields = $( [] ).add(pseudo).add(isadmin).add( name ).add(firstname)
            .add( email ).add( location),
    tips = $( ".validateTips" );
    function updateTips( t ) {
        tips
                .text( t )
                .addClass( "ui-state-highlight" );
        setTimeout(function() {
            tips.removeClass( "ui-state-highlight", 1500 );
        }, 500 );
    }
    
    function checkLength( o, n, min, max ) {
        if ( o.val().length > max || o.val().length < min ) {
            o.addClass( "ui-state-error" );
            updateTips( "Length of " + n + " must be between " +
                    min + " and " + max + "." );
            return false;
        } else {
            return true;
        }
    }
    function checkUsername( o) {
        var uvalid=true;
        $.ajax({
            url: "checkUsername?username="+o.val(),
            dataType: "json",
            async: false,
            success: function( data ) {
                if(!data["valid"]){
                    o.addClass( "ui-state-error" );
                    updateTips( "the username already exist! Please enter another username");
                    uvalid = false;
                }
            }
        });
        return uvalid;
    }
    $( "#dialog-form" ).dialog({
        autoOpen: true,
        height: 500,
        width: "60%",
        modal: true,
        buttons: {
            "Create an account": function() {
                var bValid = true;
                allFields.removeClass( "ui-state-error" );
                bValid = bValid && checkLength( pseudo, "username", 3, 16 );
                bValid = bValid && checkUsername(pseudo);
                bValid = bValid && checkLength( name, "last name", 1, 30 );
                bValid = bValid && checkLength( firstname, "first name", 1, 30 );
                bValid = bValid && checkLength( email, "email", 6, 30 );
                
                if ( bValid ) {
                    tips.text("");
                    var admin_val = isadmin.is(':checked')?"yes":"no";
                    var admin = isadmin.is(':checked')?true:false;
                    //send request to server
                    $.ajax({
                        type: 'POST',
                        dataType: 'json',
                        async: false,
                        url: 'performCreateUser?pseudo='+pseudo.val()+'&email='+email.val()+'&name='+name.val()
                                +'&firstname='+firstname.val()+'&location='+location.val()+'&isadmin='+admin,
                        timeout: 3000,
                        success: function(data) {
                            
                            if(!data["error"]){
                                $( "#users tbody" ).append( "<tr>" +
                                        "<td>" + name.val() + "</td>" +
                                        "<td>" + firstname.val() + "</td>" +
                                        "<td>" + pseudo.val() + "</td>" +
                                        "<td>" + email.val() + "</td>" +
                                        "<td>" + pseudo.val() + "</td>" +
                                        "<td>" + admin_val + "</td>" +
                                        "<td>" + location.val() + "</td>" +
                                        "</tr>" );
                                $("#error").html("<span class='glyphicon glyphicon-ok'></span> The user has been added succesfully !").addClass("create-success");
                            }
                            else{
                                $("#error").html("<span class='glyphicon glyphicon-remove'></span> Unable to create user !").addClass("create-error"); 
                            }
                            $( "#dialog-form" ).dialog( "close" );
                        },
                        error: function() {
                            $("#error").text("Unable to create user !").addClass("create-error"); 
                            $("#dialog-form").dialog( "close" );
                        }
                    });    
                    
                }
            },
            Cancel: function() {
                $( this ).dialog( "close" );
            }
        },
        close: function() {
            tips.text("");
            allFields.val( "" ).removeClass( "ui-state-error" );
        }
    });
    $( "#create-user" )
            .button()
            .click(function() {
                $( "#dialog-form" ).dialog( "open" );
    });
    $("#return-chat").button();
    $("#return-home").button();
    
    function pull_left(me, p){
        $(me).width(40);
        $( me ).position({
            my: "left left",
            at: "right+2 right ",
            collision:"flip",
            of: p
        }); 
    } 
    pull_left("#pseudo-tooltip", "#pseudo");
    pull_left("#name-tooltip", "#name");
    pull_left("#firstname-tooltip", "#firstname");
    pull_left("#email-tooltip", "#email");
    pull_left("#location-tooltip", "#location");
    pull_left("#pseudo-tooltip", "#pseudo");
    pull_left("#isadmin", "#label-admin");
    pull_left("#admin-tooltip", "#isadmin");
    
});